'''
i关爱重症海外医疗保险
'''

import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "i关爱重症海外医疗保险"

    # 生成产品数据
    def genProductInfo(self):

        plan = {

            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 66)],
                # 性别
                "gender": ["M", "F"],
                # 投保对象 1 本人投保
                "payObject": ["1"],
                # 投保计划
                "plan": ["基础款", "标准款"],
                # 保险期间
                "expire": ["1年"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(22, 66)],
                # 性别
                "gender": ["M", "F"],
                # 投保对象 2 父母
                "payObject": ["2"],
                # 投保计划
                "plan": ["基础款", "标准款"],
                # 保险期间
                "expire": ["1年"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(22, 66)],
                # 性别
                "gender": ["M", "F"],
                # 投保对象 3 配偶
                "payObject": ["3"],
                # 投保计划
                "plan": ["基础款", "标准款"],
                # 保险期间
                "expire": ["1年"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(22, 66)],
                # 性别
                "gender": ["M", "F"],
                # 投保对象 10 子女
                "payObject": ["10"],
                # 投保计划
                "plan": ["基础款", "标准款"],
                # 保险期间
                "expire": ["1年"]
            },

        }

        for k in plan:

            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["payObject"], plan[k]["plan"],
                             plan[k]["expire"]):

                if v[3] == "基础款":

                    money = "300w"

                else:

                    money = "600w"

                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], money, v[4]))

                self.mysql._conn.commit()

                print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], money, v[4]))

    # 执行爬虫
    def requestJson(self, dt=None, false="false"):


        if  ( dt["plan"]) == "基础款":

           plan = "1"

        else:

           plan = "2"

        data = [{"relationToInsured": dt["payObject"], "birthday": "{0}-01-16".format(str( 2019-int(dt["year"]))), "sex": dt["gender"], "name": "李达康", "plan": plan,
                 "amount": "30000000" if dt["plan"] =="基础款" else "6000000", "planArea": "1", "coveredYears": "1", "isRenewalInd": false, "disposable": "5",
                 "cbsProductId": 1000104 if dt["plan"] =="基础款" else 1000109, "coveredType": "2", "recommendCode": "", "payFrequency": "5",
                 "payingYears": 0, "payingType": "1"}]

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=json.dumps(data))

        if r.status_code == 200 and r.json()["alert"]:

            price = Helper.decimalParse( r.json()["data"][0]["premium"] )

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )


        else:

            data = {

                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.randTask(data)

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)





if __name__ == '__main__':
    s = Spider()

    s.main()
